package com.san.base.service.impl;

import com.san.base.dao.TaskDao;
import com.san.base.domain.ScheduleJob;
import com.san.base.domain.TaskDO;
import com.san.base.service.TaskService;
import com.san.common.quartz.utils.QuartzManager;
import com.san.common.utils.Constant;
import com.san.common.utils.ScheduleJobUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TaskServiceImpl implements TaskService {

	@Autowired
	private TaskDao taskMapper;

	@Autowired
	QuartzManager quartzManager;

	@Override
	public Object getById(Long id) {
		return taskMapper.getById(id);
	}

	@Override
	public List<TaskDO> list(Map<String, Object> map) {
		return taskMapper.list(map);
	}

	@Override
	public int count(Map<String, Object> map) {
		return taskMapper.count(map);
	}

	@Override
	public int save(Object obj) {
		return taskMapper.save(obj);
	}

	@Override
	public int doEdit(Object obj) {
		return taskMapper.doEdit(obj);
	}

	@Override
	public int remove(Long id) {
		try {
			TaskDO taskDO = (TaskDO)taskMapper.getById(id);
			quartzManager.deleteJob(ScheduleJobUtils.entityToData(taskDO));
			return taskMapper.remove(id);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return 0;
		}

	}

	@Override
	public int batchRemove(Long[] ids) {
		for (Long id : ids) {
			try {
				TaskDO scheduleJob = (TaskDO)getById(id);
				quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob));
			} catch (SchedulerException e) {
				e.printStackTrace();
				return 0;
			}
		}
		return taskMapper.batchRemove(ids);
	}

	@Override
	public void initSchedule() throws SchedulerException {
		// 这里获取任务信息数据
		List<TaskDO> jobList = taskMapper.list(new HashMap<String, Object>(16));
		for (TaskDO taskDO : jobList) {
			if (Constant.STATUS_NORMAL == taskDO.getStatus()) {
				ScheduleJob job = ScheduleJobUtils.entityToData(taskDO);
				quartzManager.addJob(job);
			}

		}
	}

	@Override
	public void changeStatus(Long jobId, String cmd) throws SchedulerException {
		TaskDO taskDO = (TaskDO)getById(jobId);
		if (taskDO == null) {
			return;
		}
		if (Constant.STATUS_RUNNING_STOP.equals(cmd)) {
			quartzManager.deleteJob(ScheduleJobUtils.entityToData(taskDO));
			taskDO.setStatus(Constant.STATUS_INVALID);
		} else {
			if (!Constant.STATUS_RUNNING_START.equals(cmd)) {
			} else {
				taskDO.setStatus(Constant.STATUS_NORMAL);
                quartzManager.addJob(ScheduleJobUtils.entityToData(taskDO));
            }
		}
		doEdit(taskDO);
	}

	@Override
	public void updateCron(Long jobId) throws SchedulerException {
		TaskDO taskDO = (TaskDO)getById(jobId);
		if (taskDO == null) {
			return;
		}
		if (Constant.STATUS_NORMAL == taskDO.getStatus()) {
			quartzManager.updateJobCron(ScheduleJobUtils.entityToData(taskDO));
		}
		doEdit(taskDO);
	}

}
